//封装购物车模块
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useCartStore = defineStore(
  "cart",
  () => {
    //1.定义state - cartList
    const cartList = ref([]);
    //2.定义action - addCart
    const addCart = (detailGoodsList) => {
      //添加购物车操作
      //已添加count++ 未添加:push到cartList数组中
      let item = cartList.value.find((item) => {
        return detailGoodsList.skuId === item.skuId;
      });
      if (item) {
        item.count++;
      } else {
        cartList.value.push(detailGoodsList);
      }
    };
    //删除购物车
    //思路：
    //1.找到需要删除的skuId - splice(skuId,1)
    //2.使用数组的过滤方法filter()
    const delCart = (skuId) => {
      //   const index = cartList.value.findIndex((item) => {
      //     return skuId === item.skuId;
      //   });
      //   cartList.value.splice(index, 1);
      // 使用 filter 方法过滤掉不需要的元素
      cartList.value = cartList.value.filter((item) => item.skuId !== skuId);
    };
    //TODO:?.更改属性selected
    const singleCheck = (selectionArr) => {
      selectionArr.forEach = (selectedItem) => {
        const index = cartList.value.findIndex((item) => {
          return item.skuId === selectedItem.skuId;
        });
        if (index !== -1) {
          cartList.value[index].selected = true;
        }
        cartList.value.forEach((item) => {
          if (!selection.find((selectedItem) => selectedItem.id === item.id)) {
            return (item.selected = false);
          }
        });
      };
    };

    // 计算属性
    //1.计算总数量
    const allCount = computed(() => {
      return cartList.value.reduce((prev, current) => {
        return prev + current.count;
      }, 0);
    });
    //2.计算总价格
    const allPrice = computed(() => {
      return cartList.value.reduce((prev, current) => {
        return prev + current.count * current.price;
      }, 0);
    });
    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
    };
  },
  {
    persist: true,
  }
);
